﻿using System.Windows.Data;
using System;
using System.Globalization;
using ClassMetadataBrowser.Domain;
using System.Windows.Media.Imaging;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;

namespace ClassMetadataBrowser.UI
{
	internal class ObjectIconConverter : IValueConverter
	{
		#region IValueConverter Members

		object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if (value == null)
				return null;
			
			BitmapImage image = new BitmapImage();
			image.BeginInit();

			MetadataImage converter = new MetadataImage();
			((MetadataObjectBase)value).Accept(converter);
			Bitmap bitmap = converter.Icon;

			MemoryStream stream = new MemoryStream();
			bitmap.MakeTransparent(bitmap.GetPixel(0, 0));
			bitmap.Save(stream, ImageFormat.Png);

			stream.Seek(0, SeekOrigin.Begin);
			image.DownloadCompleted += delegate
			{
				image.StreamSource.Close();
			};

			image.StreamSource = stream;
			image.EndInit();
			return image;
		}

		object IValueConverter.ConvertBack(object value, Type targetType,
			object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}

		#endregion
	}
}
